const router = require("koa-router")();
const util = require("../utils/utils");
const md5 = require("md5-node");
// 引入jwt
const jwt = require("jsonwebtoken");
const {
  login,
  getUserList,
  register,
  update,
  userAuth,
} = require("../controller/users");

router.prefix("/users");

router.get("/getUserInfo", async function (ctx, next) {
  const phone = ctx.request.query;

  const result = await getUserList(phone);
  if (result) {
    ctx.body = {
      code: 0,
      data: result,
    };
  } else {
    ctx.body = {
      code: 1,
    };
  }
});

router.post("/login", async function (ctx, next) {
  try {
    const userData = ctx.request.body;
    userData.password = md5(userData.password);
    let result = await login(userData);
    if (result) {
      result = result.toObject();
      delete result.password;
      // 生成并返回token,第一个参数是数据,第二个参数是密钥,第三个参数是过期时间
      const token = jwt.sign(
        {
          data: result,
        },
        "yydy",
        {
          expiresIn: "1h",
        }
      );
      result.token = token;
      ctx.body = util.success(result);
    } else {
      ctx.body = util.fail("账号或密码不正确");
    }
  } catch (error) {
    // 如果上述过程出现问题, 返回错误信息
    ctx.body = util.fail(error.msg);
  }
});
router.post("/register", async function (ctx, next) {
  const userData = ctx.request.body;
  userData.password = md5(userData.password);
  const result = await register(userData);
  ctx.body = {
    code: 0,
    data: result,
  };
});
// 忘记密码
router.post("/forgetPsd", async function (ctx, next) {
  const userData = ctx.request.body;
  userData.password = md5(userData.password);
  const result = await update(userData);
  ctx.body = {
    code: 0,
    data: result,
  };
});
// 用户认证
router.post("/auth", async function (ctx, next) {
  const userData = ctx.request.body;
  if (!userData.headImg) {
    userData.headImg = "https://yydy.love/Resouce/tom.jpg";
  }
  const result = await userAuth(userData);
  if (result) {
    ctx.body = {
      code: 0,
      data: true,
    };
  }
});
router.get("/count", async function (ctx, next) {
  ctx.body = {
    code: 0,
    data: 10,
    msg: "",
  };
});

module.exports = router;
